<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>北化论坛 - 编辑资料</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
    <h1>编辑资料</h1>
    <form id="profileForm">
        <input type="file" accept="image/*" id="profileImageInput">
        <input type="text" placeholder="新用户名" id="usernameInput" required>
        <button type="submit">保存</button>
    </form>
</div>

<script>
    // 在页面加载时，检查是否已有保存的头像和用户名
    window.onload = function() {
        const savedAvatar = localStorage.getItem('userAvatar');
        const savedUsername = localStorage.getItem('username');

        if (savedAvatar) {
            // 如果有头像，显示头像预览
            document.getElementById('profileImageInput').setAttribute('data-avatar', savedAvatar);
        }
        if (savedUsername) {
            // 如果有用户名，填充用户名字段
            document.getElementById('usernameInput').value = savedUsername;
        }
    }

    document.getElementById('profileForm').addEventListener('submit', function(event) {
        event.preventDefault();

        const profileImageInput = document.getElementById('profileImageInput');
        const usernameInput = document.getElementById('usernameInput');
        
        const avatarFile = profileImageInput.files[0];
        const username = usernameInput.value.trim();

        if (avatarFile && username) {
            // 将头像和用户名保存到 localStorage
            const reader = new FileReader();
            reader.onloadend = function() {
                const avatarDataUrl = reader.result;
                localStorage.setItem('userAvatar', avatarDataUrl);
                localStorage.setItem('username', username);

                // 提示修改成功并跳转到主页面
                alert('资料修改成功！');
                window.location.href = 'main.html';
            };
            reader.readAsDataURL(avatarFile);  // 转换头像为 base64 格式
        } else {
            alert('请上传头像并填写用户名');
        }
    });
</script>
</body>
</html>
